package com.ericsson.mq.util;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.ericsson.mq.domain.Alarm;
import com.ericsson.mq.domain.Attribute;
import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "mqAlarmConsumer")
public class SendAlarmUtil {

    private static final String URI_LOGIN = "/login";

    private static final String URI_ALARM = "/fmxadminws/v1/eventsimengine/play";

    public static int sendAlarm(String host,String username,String password,String body){
        int httpStatus = 0;
        try {
            HttpResponse loginResponse = postLogin(host, username, password);
            String responseBody = loginResponse.body();
            if (responseBody.contains("SUCCESS")) {
                HttpResponse alarmResponse = postAlarm(host, body, loginResponse.getCookieStr());
                httpStatus = alarmResponse.getStatus();
                log.debug("postAlarm httpStatus {}", httpStatus);
                alarmResponse.close();
            }else{
                httpStatus = loginResponse.getStatus();
                log.error("postLogin login failed :{}",responseBody);
            }
            loginResponse.close();
        }catch(Exception e){
            httpStatus = 500;
        }
        return httpStatus;
    }

    public static String buildAlarm(Attribute attribute){
        Alarm alarm = new Alarm();
        alarm.getSequence().get(0).setAttribute(attribute);
        return JSONUtil.parseObj(alarm, false).toString();
    }

    private static HttpResponse postLogin(String host,String username,String password){
        return HttpRequest.post("https://" + host + URI_LOGIN)
                .form("IDToken1", username)
                .form("IDToken2", password).execute();
    }

    private static HttpResponse postAlarm(String host,String body,String cookieStr){
        return HttpRequest.post("https://" + host + URI_ALARM)
                .header(Header.CONTENT_TYPE, "application/json")
                .header(Header.ACCEPT, "application/json")
                .cookie(cookieStr)
                .body(body).execute();
    }
}
